<?php

declare(strict_types=1);

namespace app\shop\middleware;

use \Firebase\JWT\JWT;
use think\Exception;

//验证token中间件
class checkToken
{
    /**
     * 处理请求
     *
     * @param think\facade\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // dump($request->header('cookie'));
        if ($request->isPost()) {
            $token = $request->header('Authorization');
            if (isset($token)) {
                $key = '1164601554@qq.com'; //key要和签发的时候一样
                try {
                    JWT::$leeway = 60; //当前时间减去60，把时间留点余地
                    $decoded = JWT::decode($token, $key, ['HS256']); //HS256方式，这里要和签发的时候对应
                    $arr = (array)$decoded;
                    $request->token = json_decode($arr['data'], true);
                } catch (\Firebase\JWT\SignatureInvalidException $e) {  //签名不正确
                    return json(['code' => 1, 'msg' => $e->getMessage()]);
                } catch (\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用
                    return json(['code' => 1, 'msg' => $e->getMessage()]);
                } catch (\Firebase\JWT\ExpiredException $e) {  // token过期
                    return json(['code' => 1, 'msg' => $e->getMessage()]);
                } catch (Exception $e) {  //其他错误
                    return json(['code' => 1, 'msg' => $e->getMessage()]);
                }
            }
        }
        return $next($request);
    }
}
